/*
 * SwSPI.cpp
 *
 *  Created on: 10.1.2013
 *      Author: lukas
 */

#include "SwSPI.hpp"
#include "wiringPi.h"
#include "stdlib.h"


void  ToBin ( int number, int* numberBin )
{

int i;
	bool b[sizeof(unsigned)*8];


	b[0] = number & 0x1;	//vrati bit s najnizsou vahou
	b[1] = number & 0x2;	//vrati bit s 2 najnizsou vahou
	b[2] = number & 0x4;
	b[3] = number & 0x8;
	b[4] = number & 0x10;
	b[5] = number & 0x20;
	b[6] = number & 0x40;
	b[7] = number & 0x80;//MSB

	for (i=0;i<8;i++)
	{
	if (b[i])
		numberBin[i]=1;
	else
		numberBin[i]=0;
	}

}

int  BinTo (int* numberBin)
{
	int i,result=0;
for (i=7;i>0;i--)
{
result += numberBin[i];
result = result << 1;
}
result += numberBin[0];

return result;
}

int SwSpiInit(void)
{
	if (wiringPiSetup () == -1)
	     exit (1) ;

	pinMode (MISO, INPUT);
	pinMode (MOSI, OUTPUT);
	pinMode (SPICLK, OUTPUT);
	pinMode (CS_SPI1, OUTPUT);
	digitalWrite(CS_SPI1, HIGH);
	digitalWrite(SPICLK, LOW);
	digitalWrite(MOSI, LOW);



return 0;
}

void SwSpiRW(int ChSelect, int* buffer, int PocetSlov) {
	int RXbuff[8];
	int TXbuff[8];
	int i = 0, y = 0;



	digitalWrite(ChSelect, LOW); 	//výběr čipselktu úroveň down
	delayMicroseconds(SPIT1);

for (y=0;y<PocetSlov; y++)
{
	ToBin(buffer[y], RXbuff);
	for (i=8; i>0;i--)
	{
		digitalWrite(SPICLK, HIGH);
		digitalWrite(MOSI,RXbuff[i]);
		delayMicroseconds(SPIT2);
		digitalWrite(SPICLK, LOW);
		TXbuff[i] = digitalRead(MISO);
		delayMicroseconds(SPIT3);
	}
delayMicroseconds(SPIT7);
buffer[y] = BinTo(TXbuff);
}
}
